package com.example.administrator.newsreading;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.SearchView;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.example.administrator.newsreading.Bean.news;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    //查询条件
    private ArrayList<String> query_category = new ArrayList<String>();
    private String query_keyWord = null;

    //下拉刷新
    private SwipeRefreshLayout swipeRefreshLayout = null;

    //ListView
    private ListView listView;

    //生成动态数组，用来加载数据
    private ArrayList<HashMap<String, Object>> news_list = new ArrayList<HashMap<String, Object>>();

    //Toolbar
    Toolbar toolbar;

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bmob.initialize(this, "24e89d3c1e746bd3d1d0f3a3fc14657d");
        deleteOverdueNews();

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //绑定下拉刷新控件的ID
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh);
        //绑定XML中的ListView，作为Item的容器
        listView = (ListView) findViewById(R.id.listView);

        //下拉刷新的监听器
        swipeRefreshLayout.setOnRefreshListener(listener);
        listener.onRefresh();

       //设定ListView的点击触发事件
       listView = (ListView) findViewById(R.id.listView);
       listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               Intent intent = new Intent();
               intent.setClass(MainActivity.this, detail.class);

               //获取选中项的HashMap对象
               HashMap<String, Object> map = (HashMap<String, Object>) listView.getItemAtPosition(position);
               intent.putExtra("ID", (String)map.get("Item_ID"));

               startActivity(intent);
           }
       });
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        //SearchView配置
        MenuItem menuItem = menu.findItem(R.id.toolbar_search);//在菜单中找到对应控件的item
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);

        //设置SearchView的查询触发器
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query)
            {
                toolbar.setTitle(query);
                query_category.clear();
                query_keyWord = null;
                query_keyWord = query;
                add_data();
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        //int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        //if (id == R.id.action_settings) {
        //    return true;
        //}

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_today) {
            // Handle the camera action
            toolbar.setTitle("首页");
            query_category.clear();
            query_keyWord = null;
            add_data();
        } else if (id == R.id.nav_globe) {
            toolbar.setTitle("世界");
            query_category.clear();
            query_keyWord = null;
            query_category.add("w");
            query_category.add("o");
            query_category.add("news");
            add_data();
        } else if (id == R.id.nav_domestic) {
            toolbar.setTitle("国内");
            query_category.clear();
            query_keyWord = null;
            query_category.add("c");
            add_data();
        } else if (id == R.id.nav_society) {
            toolbar.setTitle("社会");
            query_category.clear();
            query_keyWord = null;
            query_category.add("s");
            add_data();
        } else if (id == R.id.nav_sports) {
            toolbar.setTitle("体育");
            query_category.clear();
            query_keyWord = null;
            query_category.add("sports");
            add_data();
        } else if (id == R.id.nav_ent) {
            toolbar.setTitle("娱乐");
            query_category.clear();
            query_keyWord = null;
            query_category.add("ent");
            add_data();
        } else if (id == R.id.nav_finance) {
            toolbar.setTitle("财经");
            query_category.clear();
            query_keyWord = null;
            query_category.add("money");
            query_category.add("finance");
            add_data();
        } else if (id == R.id.nav_tec) {
            toolbar.setTitle("科技");
            query_category.clear();
            query_keyWord = null;
            query_category.add("tech");
            add_data();
        } else if (id == R.id.nav_mil) {
            toolbar.setTitle("军事");
            query_category.clear();
            query_keyWord = null;
            query_category.add("war");
            query_category.add("mil");
            add_data();
        } else if (id == R.id.nav_edu) {
            toolbar.setTitle("教育");
            query_category.clear();
            query_keyWord = null;
            query_category.add("edu");
            add_data();
        } else if (id == R.id.nav_phone) {
            toolbar.setTitle("手机");
            query_category.clear();
            query_keyWord = null;
            query_category.add("mobile");
            add_data();
        } else if (id == R.id.nav_digi) {
            toolbar.setTitle("数码");
            query_category.clear();
            query_keyWord = null;
            query_category.add("digi");
            add_data();
        } else if (id == R.id.nav_car) {
            toolbar.setTitle("汽车");
            query_category.clear();
            query_keyWord = null;
            query_category.add("auto");
            add_data();
        } else if (id == R.id.nav_travel) {
            toolbar.setTitle("旅游");
            query_category.clear();
            query_keyWord = null;
            query_category.add("travel");
            add_data();
        } else if (id == R.id.nav_baby) {
            toolbar.setTitle("亲子");
            query_category.clear();
            query_keyWord = null;
            query_category.add("baby");
            add_data();
        } else if (id == R.id.nav_game) {
            toolbar.setTitle("游戏");
            query_category.clear();
            query_keyWord = null;
            query_category.add("play");
            query_category.add("games");
            add_data();
        } else if (id == R.id.nav_book) {
            toolbar.setTitle("读书");
            query_category.clear();
            query_keyWord = null;
            query_category.add("book");
            add_data();
        } else if (id == R.id.nav_cul){
            toolbar.setTitle("文化");
            query_category.clear();
            query_keyWord = null;
            query_category.add("cul");
            add_data();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    //设置下拉刷新控件的监听器
    SwipeRefreshLayout.OnRefreshListener listener = new SwipeRefreshLayout.OnRefreshListener(){
        @Override
        public void onRefresh() {
            add_data();
            swipeRefreshLayout.setRefreshing(false);
        }
    };

    public void add_data(){
        listView.setAdapter(null);
        news_list.clear();
        BmobQuery<news> mainQuery = new BmobQuery<news>();

        //每次点击种类之后，query_category改变，并且将query_keyWord置为空
        //当输入关键词查询是，query_keyWord改变，query_category置为空
        //默认情况下两者都为空，执行 今日 查询
        //两者中某一个不为空，执行那个；全为空，执行默认查询
        if (query_category.size() != 0){
            mainQuery.addWhereContainedIn("category", query_category);
        }
        if (query_keyWord != null){
            mainQuery.addWhereContains("title", query_keyWord);
        }
        if ((query_category.size()==0) && (query_keyWord==null)){
            mainQuery.addWhereContains("time", getDate());
        }

        //过滤掉空标题新闻
        mainQuery.addWhereNotEqualTo("title", "");
        //限制查询结果条数为50条，默认为10条
        mainQuery.setLimit(50);
        //按时间降序
        mainQuery.order("-time");
        //执行查询
        mainQuery.findObjects(this, new FindListener<news>() {
            @Override
            public void onSuccess(List<news> list) {
                for(news item : list){
                    if ((item.getTitle()+"a").length() > 5) {//过滤无效新闻
                        //向动态数组里面加载查询到的数据
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        map.put("Item_ID", item.getID());
                        map.put("Item_title", item.getTitle());
                        map.put("Item_source", convert_source(item.getSource()));
                        map.put("Item_time", convert_time(item.getTime()));
                        map.put("Item_ID", item.getID());
                        news_list.add(map);
                    }
                }

                //生成适配器，数组==》ListItem
                SimpleAdapter schedule = new SimpleAdapter(MainActivity.this, //当前上下文
                        news_list,  //数据来源
                        R.layout.list_item,  //list_item的xml实现
                        new String[] {"Item_title", "Item_source" , "Item_time", "Item_ID"},  //动态数组与list_item对应的子项
                        new int[] {R.id.Item_title, R.id.Item_source, R.id.Item_time, R.id.Item_ID});  //list_item的xml文件中4个TextView ID

                //添加并显示
                listView.setAdapter(schedule);

            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    //转换来源信息
    private String convert_source(String source){
        String result = null;
        if(source.equals("sina")){
            result = "新浪";
        }
        else if (source.equals("tencent")){
            result = "腾讯";
        }
        else if (source.equals("netease")){
            result = "网易";
        }
        return result;
    }

    //转换时间信息，将12位的时间转化为mm-dd hh:mm
    private String convert_time(String time){
        String result;
        String month, day, hour, minute;
        month = time.substring(4,6);
        day = time.substring(6,8);
        hour = time.substring(8,10);
        minute = time.substring(10,12);

        result = month + "-" + day + " " + hour + ":" + minute;

        return result;
    }

    //获取今日日期
    private String getDate() {
        String time;
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        time = simpleDateFormat.format(date);

        return time;
    }

    //删除旧新闻
    private void deleteOverdueNews(){
        Date date = new Date(System.currentTimeMillis()-5*24*60*60*1000);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmm");
        String time = simpleDateFormat.format(date);

        BmobQuery<news> query = new BmobQuery<news>();
        query.addWhereLessThan("time", time);
        query.setLimit(50);
        query.findObjects(this, new FindListener<news>() {
            @Override
            public void onSuccess(List<news> list) {
                news news1 = new news();

                for (news item : list){
                    news1.setObjectId(item.getObjectId());
                    news1.delete(MainActivity.this);
                }
                //Toast.makeText(MainActivity.this, "成功删除过期新闻", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(int i, String s) {

            }
        });

    }

}
